package nl.vu.few.ibivu.biomodels.client.presenter;

import java.util.List;

import nl.vu.few.ibivu.biomodels.client.GwtRpcResultList;
import nl.vu.few.ibivu.biomodels.client.PagerServiceAsync;
import nl.vu.few.ibivu.biomodels.client.event.MessageBroadcastType;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;

public abstract class AbstractPager<T> extends AbstractPresenter implements PagerPresenter<T> {

	public static final int DEFAULT_PAGESIZE = 10;
	private int pageSize;
	private PagerServiceAsync<T> pagerService;
	private String cursor;
	
	@Inject
	public AbstractPager(EventBus eventBus, PlaceController placeControl, PagerServiceAsync<T> pagerService) {
		super(eventBus, placeControl);
		this.pagerService = pagerService;
		this.pageSize = DEFAULT_PAGESIZE;
		this.cursor = null;
	}
	
	public void getNextPage() {
		// FIXME add order string instead of null
		pagerService.fetch(cursor, pageSize, null, new AsyncCallback<GwtRpcResultList<T>>(){

			@Override
			public void onFailure(Throwable caught) {
				broadcastMessage(MessageBroadcastType.ERROR, caught.getMessage());
			}

			@Override
			public void onSuccess(GwtRpcResultList<T> result) {
				cursor = result.getNextCursor();
				pageReceived(result, result.getTotalRows());
			}});
	}
	
	public String getCursor() {
		return cursor;
	}
	
	public void setCursor(String cursor) {
		this.cursor = cursor;
	}

	public abstract void pageReceived(List<T> results, int totalRows);
}
